<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'
import {
  ElectricalControlClassification,
  ElectricalControlClassificationListParam,
} from '@/api/electrical/type'
import {
  addClassificationApi,
  editClassificationApi,
  deleteClassificationApi,
  getClassificationListApi,
  getSimpleClassificationListApi,
} from '@/api/electrical'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import TreeSelect from '@/components/TreeSelect/index.vue'

// ----------------------- 组件状态定义 -----------------------
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()

// 当前选中的分类ID，用于树形筛选
const currentCategoryId = ref<number>()

// 查询表单数据，包含分页信息
const searchForm = reactive<ElectricalControlClassificationListParam>({
  name: undefined,
  parentId: undefined,
  page: 1,
  limit: 10,
})

// 表格数据和总条数和加载效果
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 表单ref，用于表单验证
const addFormRef = ref<FormInstance>()

// 新增/编辑表单数据
const addForm = reactive<ElectricalControlClassification>({
  id: undefined,
  name: undefined,
  remark: undefined,
  parentId: undefined,
})

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表单验证规则 -----------------------
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择上级分类', trigger: 'change' }],
}

// ----------------------- 树形数据处理 -----------------------
// 上级分类选择器的数据
const parentOptions = ref<any[]>([])

/**
 * 获取上级分类列表数据
 * 用于新增/编辑表单中的上级分类选择
 */
const getParentCategories = async () => {
  try {
    const res = await getSimpleClassificationListApi()
    if (res?.data) {
      const treeData = handleParentTree(res.data)
      // 添加顶级节点
      parentOptions.value = [
        {
          id: '0',
          value: '0',
          label: '顶级分类',
          children: treeData,
        },
      ]
    }
  } catch (error) {
    console.error('获取上级分类列表失败:', error)
    ElMessage.error('获取上级分类列表失败')
  }
}

/**
 * 处理上级分类树形数据
 * @param data 原始数据
 * @returns 处理后的树形数据
 */
const handleParentTree = (data: any[]) => {
  const map = new Map()
  const result: any[] = []

  // 初始化映射表
  data.forEach((item) => {
    map.set(item.id, {
      id: item.id,
      value: item.id,
      label: item.name, // 使用 name 字段作为标签
      children: [],
    })
  })

  // 构建树形结构
  data.forEach((item) => {
    const node = map.get(item.id)
    if (item.parentId === '0') {
      result.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })
  return result
}

// ----------------------- 左侧筛选树形数据处理 -----------------------
// 定义树节点类型
interface TreeNode {
  id: string
  name: string
  parentId: string
  children: TreeNode[]
}

// 左侧筛选树形数据
const treeData = ref<TreeNode[]>([])

/**
 * 获取左侧筛选树形数据
 */
const getTreeData = async () => {
  try {
    const res = await getSimpleClassificationListApi()
    if (res?.data) {
      treeData.value = handleTree(res.data)
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

/**
 * 处理左侧筛选树形结构
 * @param data 原始数据
 * @returns 处理后的树形数据，包含虚拟顶级节点
 */
const handleTree = (data: TreeNode[]): TreeNode[] => {
  const map = new Map<string, TreeNode>()
  const result: TreeNode[] = []

  // 创建虚拟的顶级节点
  const rootNode: TreeNode = {
    id: '-1',
    name: '全部分类',
    parentId: '',
    children: [],
  }

  // 初始化映射表
  data.forEach((item) => {
    map.set(item.id, { ...item, children: [] })
  })

  // 构建树形结构
  data.forEach((item) => {
    const node = map.get(item.id)!
    if (item.parentId === '0') {
      rootNode.children.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  result.push(rootNode)
  return result
}

// ----------------------- CRUD 操作方法 -----------------------
/**
 * 获取分类列表数据
 */
const getList = async () => {
  loading.value = true
  try {
    const res = await getClassificationListApi(searchForm)
    if (res?.data) {
      tableData.value = res.data.list
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取列表数据失败:', error)
    ElMessage.error('获取列表数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 重置查询表单
 */
const resetForm = () => {
  searchForm.name = undefined
  searchForm.parentId = currentCategoryId.value || undefined
  searchForm.page = 1
  getList()
}

/**
 * 显示新增弹框
 */
const show = () => {
  dialog.title = '新增电控物料分类'
  dialog.width = 600
  dialog.height = 400
  nextTick(() => {
    addFormRef.value?.resetFields()
  })
  onShow()
}

/**
 * 显示编辑弹框
 */
const edit = (row: ElectricalControlClassification) => {
  dialog.title = '编辑电控物料分类'
  dialog.width = 600
  dialog.height = 400
  nextTick(() => {
    Object.assign(addForm, row)
  })
  onShow()
}

/**
 * 删除分类
 */
const del = async (id: number) => {
  const confirm = await global.$myConfirm('您确定删除该数据吗？')
  if (confirm) {
    try {
      const res = await deleteClassificationApi(id)
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        getList()
        getTreeData() // 刷新树形数据
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 保存分类（新增/编辑）
 */
const save = async () => {
  if (!addFormRef.value) return
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (addForm.id) {
          res = await editClassificationApi(addForm)
        } else {
          res = await addClassificationApi(addForm)
        }
        if (res && res.code === 200) {
          ElMessage.success(addForm.id ? '修改成功' : '新增成功')
          onClose()
          getList()
          getTreeData() // 刷新树形数据
          addFormRef.value?.resetFields()
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// ----------------------- 分页相关方法 -----------------------
/**
 * 页码改变处理
 */
const handleCurrentChange = (val: number) => {
  searchForm.page = val
  getList()
}

/**
 * 每页条数改变处理
 */
const handleSizeChange = (val: number) => {
  searchForm.limit = val
  getList()
}

/**
 * 关闭弹框
 */
const closeDialog = () => {
  addFormRef.value?.resetFields()
  onClose()
}

/**
 * 树节点点击事件处理
 */
const handleTreeNodeClick = async (data: any) => {
  // 处理虚拟顶级节点点击
  if (data.id === '-1') {
    currentCategoryId.value = undefined
    searchForm.parentId = undefined
  } else {
    currentCategoryId.value = data.id
    searchForm.parentId = data.id
  }

  // 重置分页和搜索条件
  searchForm.page = 1
  searchForm.limit = 10
  searchForm.name = undefined

  await getList()
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 280
  })
  // 初始化数据
  getTreeData()
  getList()
  getParentCategories()
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 280
  })
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <el-main class="electrical-category-main">
    <div class="main-container">
      <el-row :gutter="20">
        <!-- 左侧树形菜单 -->
        <el-col :span="4">
          <el-card class="tree-card"
                   shadow="hover">
            <div class="tree-header">
              <i class="el-icon-menu"></i>
              <span>电控物料分类</span>
            </div>
            <TreeSelect :data="treeData"
                        :props="{
                children: 'children',
                label: 'name'
              }"
                        placeholder="请输入分类名称"
                        @node-click="handleTreeNodeClick"
                        class="category-tree" />
          </el-card>
        </el-col>

        <!-- 右侧内容区 -->
        <el-col :span="20">
          <!-- 查询表单区域 -->
          <el-card class="search-card"
                   shadow="hover">
            <el-form :inline="true"
                     :model="searchForm"
                     class="search-form">
              <el-form-item label="分类名称">
                <el-input v-model="searchForm.name"
                          placeholder="请输入分类名称"
                          prefix-icon="Search"
                          clearable />
              </el-form-item>
              <el-form-item class="search-buttons">
                <el-button type="primary"
                           :icon="Search"
                           @click="getList"
                           class="search-btn">
                  查询
                </el-button>
                <el-button :icon="Refresh"
                           @click="resetForm"
                           class="reset-btn">
                  重置
                </el-button>
                <el-button type="success"
                           :icon="Plus"
                           @click="show"
                           class="add-btn">
                  新增
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 表格区域 -->
          <el-card class="table-card"
                   shadow="hover">
            <el-table v-loading="loading"
                      :data="tableData"
                      border
                      :height="tableHeight"
                      class="data-table">
              <el-table-column type="index"
                               label="序号"
                               width="70"
                               align="center" />
              <el-table-column prop="name"
                               label="分类名称"
                               min-width="120"
                               align="center" />
              <el-table-column prop="remark"
                               label="备注"
                               min-width="180"
                               align="center"
                               show-overflow-tooltip />
              <el-table-column prop="createTime"
                               label="创建时间"
                               min-width="170"
                               align="center" />
              <el-table-column prop="updateTime"
                               label="更新时间"
                               min-width="170"
                               align="center" />
              <el-table-column label="操作"
                               width="160"
                               fixed="right"
                               align="center">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button type="primary"
                               size="small"
                               :icon="Edit"
                               @click="edit(scope.row)"
                               class="edit-btn">
                      编辑
                    </el-button>
                    <el-button type="danger"
                               size="small"
                               :icon="Delete"
                               @click="del(scope.row.id)"
                               class="delete-btn">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination v-model:current-page="searchForm.page"
                           v-model:page-size="searchForm.limit"
                           :page-sizes="[10, 20, 30, 40, 50]"
                           :total="total"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           layout="total, sizes, prev, pager, next, jumper"
                           class="pagination" />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 新增/编辑弹框 -->
    <sys-dialog :title="dialog.title"
                :width="dialog.width"
                :visible="dialog.visible"
                :height="dialog.height"
                @onClose="closeDialog"
                @onConfirm="save">
      <template #content>
        <div class="dialog-content">
          <el-form ref="addFormRef"
                   :model="addForm"
                   :rules="rules"
                   label-width="100px"
                   class="add-form">
            <el-card class="form-card"
                     shadow="never">
              <template #header>
                <div class="form-header">
                  <span>基本信息</span>
                </div>
              </template>
              <el-form-item label="分类名称"
                            prop="name">
                <el-input v-model="addForm.name"
                          placeholder="请输入分类名称" />
              </el-form-item>
              <el-form-item label="上级分类"
                            prop="parentId">
                <el-tree-select v-model="addForm.parentId"
                                :data="parentOptions"
                                :render-after-expand="false"
                                show-checkbox
                                check-strictly
                                class="full-width" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="addForm.remark"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入备注" />
              </el-form-item>
            </el-card>
          </el-form>
        </div>
      </template>
    </sys-dialog>
  </el-main>
</template>

<style scoped lang="scss">
.electrical-category-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.tree-card {
  border-radius: 8px;
  height: calc(100vh - 100px);
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .tree-header {
    padding: 12px 0;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #67c23a;
    border-bottom: 1px solid #e1f3d8;

    i {
      margin-right: 8px;
    }
  }

  .category-tree {
    flex: 1;
    overflow: auto;
    scrollbar-width: thin;
    scrollbar-color: rgba(144, 147, 153, 0.3) transparent;

    /* 隐藏webkit浏览器滚动条，仅在悬停时显示 */
    &::-webkit-scrollbar {
      width: 6px;
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background-color: transparent;
      border-radius: 10px;
    }

    /* 鼠标悬停时显示滚动条 */
    &:hover::-webkit-scrollbar-thumb {
      background-color: #dddee0;
    }

    :deep(.el-tree-node__content) {
      height: 36px;

      &:hover {
        background-color: #f0f9eb;
      }
    }

    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: #e1f3d8;
      color: #67c23a;
    }
  }

  :deep(.el-card__body) {
    height: 100%;
    padding: 15px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;

  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }

  .search-buttons {
    margin-left: auto;

    .el-button {
      margin-left: 8px;
      transition: all 0.3s;

      &:first-child {
        margin-left: 0;
      }
    }

    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;

      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }

    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;

      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }

    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 180px);
  margin-bottom: 0;

  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;

  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }

  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }

  .action-buttons {
    display: flex;
    justify-content: center;

    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }

    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

.dialog-content {
  padding: 10px;
}

.add-form {
  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;

    &:last-child {
      margin-bottom: 0;
    }

    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }

    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
  }

  :deep(.el-input),
  :deep(.el-select),
  :deep(.el-tree-select) {
    width: 100%;
  }

  :deep(.el-input__wrapper),
  :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;

    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }

    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.full-width {
  width: 100%;
}
</style>
